package tools

import (
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/spf13/viper"
)

/*
 +----------------------------------------------------------------------
 + Title        : 助手函数
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2024-09-22
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 助手函数
 +----------------------------------------------------------------------
*/

/**
 * 错误
 *
 * @param string message -------------------------------------必传
 * @param []interface{} params -------------------------------非必传
 * @return map[string]interface{}
 * @author huwl
 */
func Error(message string, params ...interface{}) map[string]interface{} {
	status := 400
	data := map[string]interface{}{}
	if len(params) == 1 {
		status = params[0].(int)
	}
	if len(params) == 2 {
		data = params[1].(map[string]interface{})
	}
	return map[string]interface{}{
		"status_code": status,
		"msg":         message,
		"data":        data,
	}
}

/**
 * 成功
 *
 * @param string message -------------------------------------必传
 * @param []interface{} params -------------------------------非必传
 * @return map[string]interface{}
 * @author huwl
 */
func Success(data interface{}, params ...interface{}) map[string]interface{} {
	status := 200
	message := ""
	if len(params) == 1 {
		status = params[0].(int)
	}
	if len(params) == 2 {
		message = params[1].(string)
	}
	return map[string]interface{}{
		"status_code": status,
		"msg":         message,
		"data":        data,
	}
}

/**
 * 获取应用路径
 *
 * @return string
 * @author huwl
 */
func GetAppPath() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	index := strings.LastIndex(path, string(os.PathSeparator))

	return path[:index]
}

/**
 * 获取配置数据
 *
 * @param string configName ----------------------------------必传
 * @param string configType ----------------------------------必传
 * @return *viper.Viper, error
 * @author huwl
 */
func GetConfig(configName, configType string) (*viper.Viper, error) {
	v := viper.New()
	// v.AddConfigPath(GetAppPath() + "/config/")
	v.AddConfigPath("./config/")
	v.SetConfigName(configName)
	v.SetConfigType(configType)
	err := v.ReadInConfig()
	return v, err
}
